package com.walter.learn.ReadAndWrite;

import org.slf4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: learnOwner
 * @Package: com.walter.learn.ReadAndWrite
 * @ClassName: Read
 * @Description: java类作用描述
 * @Author: 唐朝
 * @CreateDate: 2019/2/19 10:46
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/2/19 10:46
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Slf4j
public class Read {

    //通过InputStreamReader方式读取文件(速度更快一点)
    public static List<String> readByInputStreamReader(String fileName) {
        List<String> list = new ArrayList<>();

        File file = new File(fileName);
        if (file.isFile() && file.exists()) {
            try {
                InputStreamReader reader = new InputStreamReader(
                        new FileInputStream(file), "UTF-8"); // 建立一个输入流对象reader
                BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                String line = "";
                while ((line = br.readLine()) != null) {
                    list.add(line);
                }
                //关闭流
                br.close();
                reader.close();
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new RuntimeException();
            }
        }
        return list;
    }

    //通过FileReader方式读取文件(速度较慢)
    public static List<String> readByFileReader(String fileName) {
        List<String> list = new ArrayList<>();
        try {
            File file = new File(fileName);
            if (file.exists()) {
                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                String line="";
                // 按行读取字符串
                while ((line = br.readLine()) != null) {
                    list.add(line);
                }
                br.close();
                fr.close();
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException();
        }
        return list;
    }
}
